#include <iostream>

#include "Settings.h"
#include <libconfig.hh>

using namespace libconfig;

using namespace skelepp::Core::Application;

Settings::Settings(void) {
	try {
		_config.readFile("include\\core.conf");
		_load();
	} catch(const FileIOException &fioex) {
		cout << "I/O error while reading file." << endl;
		return;
	} catch(const ParseException &pex) {
		cout << "Parse error at " << pex.getFile() << ":" << pex.getLine()
				<< " - " << pex.getError() << endl;
		return;
	}
}

Settings::~Settings(void) {

}

void Settings::_load(void) {
	_application_debug_level = read_uint("application.debug_level");
	_application_log_file = read_string("application.log_file");
	_application_worker_threads = read_uint("application.worker_threads");

	_network_role = read_string("network.role");
	_network_port = read_uint("network.port");
	_network_protection = read_string("network.protection");
	_network_rules = read_string_list("network.rules");

	_master_max_slaves = read_uint("master.max_slaves");

	_slave_master_server = read_string("slave.master_server");
}

string Settings::read_string(const char *path) {
	try {
		return (const char *)_config.lookup(path);
	} catch(const SettingNotFoundException &nfex) {
		cout << "No setting in configuration file." << endl;
	}
	return "";
}

uint32_t Settings::read_uint(const char *path) {
	try {
		uint32_t value;
		_config.lookupValue(path, value);
		return value;
	} catch(const SettingNotFoundException &nfex) {
		cout << "No setting in configuration file." << endl;
	}
	return 0;
}

int32_t Settings::read_int(const char *path) {
	try {
		int32_t value;
		_config.lookupValue(path, value);
		return value;
	} catch(const SettingNotFoundException &nfex) {
		cout << "No setting in configuration file." << endl;
	}
	return 0;
}

float Settings::read_float(const char *path) {
	try {
		float value;
		_config.lookupValue(path, value);
		return value;
	} catch(const SettingNotFoundException &nfex) {
		cout << "No setting in configuration file." << endl;
	}
	return 0;
}

vector<string> Settings::read_string_list(const char *path) {
	vector<string> list;
	try {
		Setting &_array = _config.lookup(path);
		for (int i = 0; i < _array.getLength(); i++) {
			list.push_back(string(_array[i].c_str()));
		}
	} catch(const SettingNotFoundException &nfex) {
		cout << "No setting in configuration file." << endl;
	}
	return list;
}